package com.xukehong.frame.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.xukehong.frame.entity.Role;
import com.xukehong.frame.entity.User;
import com.xukehong.frame.entity.UserRole;
import com.xukehong.frame.model.UserAddModel;
import com.xukehong.frame.service.IRoleService;
import com.xukehong.frame.service.IUserRoleService;
import com.xukehong.frame.service.IUserService;
import com.xukehong.frame.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户表
 * 前端控制器
 * </p>
 *
 * @author 许克弘
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;

    @ApiOperation("创建用户")
    @PostMapping("/add")
    @ApiImplicitParam(name = "roleName", value = "角色", dataType = "String", paramType = "query",
            allowableValues = "ROLE_SUPER_ADMIN,ROLE_ADMIN,ROLE_USER", allowMultiple = true)
    public R add(@RequestBody UserAddModel userAddModel) {
        //判断用户名是否重复
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("username", userAddModel.getUsername());
        User userWrapper = userService.selectOne(wrapper);
        if (ObjectUtils.isEmpty(userWrapper)) {
            User user = new User();
            user.setUsername(userAddModel.getUsername());
            user.setEmail(userAddModel.getEmail());
            user.setPassword(new BCryptPasswordEncoder().encode(userAddModel.getPassword()));
            user.setStatus(1);
            userService.resultUserId(user);
            System.out.println("返回的UserId"+user.getUserId());

            //根据角色查询roleId
            Wrapper wrapperRole = new EntityWrapper();
            wrapperRole.eq("name", userAddModel.getRoleName());
            Role role = roleService.selectOne(wrapperRole);

            //插入用户角色表
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(role.getRoleId());
            userRoleService.insert(userRole);

            return R.ok("创建成功");
        } else {
            return R.error("用户名重复");
        }
    }


}
